package imlayer

import (
	"fmt"
	"dhfshop/models/isv"
    "dhfshop/utils/helper"
	"dhfshop/models/im"
	"dhfshop/models/member"
	"dhfshop/service/redisgo"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"wxsdk/miniapp/message/custom/miniapp"
	"wxsdk/oauth"
)

func ForwardSubscribeEvent(msg *im.WxMsgReceiptRecords, eventKey string) error {
    members := &member.MemberValue{OpenID:msg.FromUserName, IsSubScribe:true}
	if err := member.UpdateMemberByOpenId(members, "is_subscribe"); err != nil {
		//beego.Debug(err.Error())
	}
	redisconn := redisgo.GetInstance()
	if msg.AppId == "wx204da65aa7d948b0" {
	    //beego.Debug("subscribe eventkey:", eventKey)
		if prefixCode := helper.Substr(eventKey, 8, 4); prefixCode == "1100" {
		    if _, err := member.GetMemberByOpenId(msg.FromUserName); err == orm.ErrNoRows {
				if custAccount, err := isv.GetCustAccountByAppId(msg.AppId); err == nil {
					if rslt, err := oauth.GetUserInfo2(custAccount.AccessToken, msg.FromUserName); err == nil {
						if _, err = member.CreateWeChatMember(msg.AppId, rslt.Unionid, rslt, 0); err != nil {
						   beego.Debug(err.Error())
						}
					}   
				}
			}
			if members, err := member.GetMemberByOpenId(msg.FromUserName); err == nil && len(members.Unionid) > 5 {
			    cacheKey := fmt.Sprintf("%s%d", members.Unionid, 1100)
			    beego.Debug("redis set cacheKey:", cacheKey)
				cacheValue := helper.Substr(eventKey, 8, len(eventKey)-8)
				if _, err = redisconn.Set(cacheKey, cacheValue, 10*60); err == nil {
			        if custAccount, err := isv.GetCustAccountByAppId(msg.AppId); err == nil {
					   miniapp.SendTextMessage(custAccount.AccessToken,msg.FromUserName,"恭喜! 安全校验已通过! 你可以正常使用大黄蜂小程序了！")
					}
			    }else{
				    beego.Debug("SETEX", err.Error())
				}
			}
		}
	}
	if cfg, err := im.GetAutoRspCfgByAppId(msg.AppId); err == nil {
		switch cfg.SubscribeReplyOpen {
			case "1":
				if custAccount, err := isv.GetCustAccountByAppId(msg.AppId); err == nil {
				    if cfg.SubscribeReplyType == "image" {
						if dstMsgBody, err := getActuralMediaId(cfg.SubscribeReplyInfo); err == nil {
							SendPubCustomerMessage(msg.AppId,custAccount.AccessToken,msg.FromUserName,cfg.SubscribeReplyType, dstMsgBody)
						}
					}else{
						SendPubCustomerMessage(msg.AppId,custAccount.AccessToken,msg.FromUserName,cfg.SubscribeReplyType, cfg.SubscribeReplyInfo)   
					}
				}
			default:	
		}
	}
	return nil
}
